<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/layui/layui.js"></script>
    <%--<link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <script src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>--%>
</head>
<body>
<%--添加和修改的弹出框--%>
<%--<div id="addRoleDiv" style="display: none">--%>
<form style="display: none" class="layui-form" id="editForm" lay-filter="editForm">
    <input name="roleid" style="display: none">
    <br>
    <div class="layui-form-item">
        <label class="layui-form-label">角色名</label>
        <div class="layui-input-inline">
            <input type="text" name="rolename" id="rolename" required placeholder="请输入角色名" class="layui-input" lay-verify="requiredname">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">角色描述</label>
        <div class="layui-input-inline">
            <input type="text" name="remark" required placeholder="请输入角色描述" class="layui-input" lay-verify="required">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">角色状态</label>
        <div class="layui-input-inline">
            <select  name="status" lay-verify="required">
                <option value="请选择">--请选择--</option>
                <option value="0">禁用</option>
                <option value="1">启用</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button id="btnSub" class="layui-btn" lay-submit lay-filter="editRole">确认</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<%--</div>--%>
<table class="layui-hide" id="test" lay-filter="test"></table>
<div id="treeDemo" style="display: none">
    <div id="test1"></div>
    <%--提交修改权限的按钮--%>




    <button class="layui-btn layui-btn-sm" id="subPer">提交权限修改</button>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        {{#  if(${sessionScope.staff.branchid} == 12138){ }}
        <button class="layui-btn layui-btn-sm" lay-event="addRole">新增角色</button>
        {{#  } else { }}
        {{#  } }}
        <button class="layui-btn layui-btn-sm" lay-event="refresh">刷新表格</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    {{# if(d.status==1){  }}
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="editPermission">修改权限</a>
    {{# }else{ }}
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{# } }}
</script>
<script>
    layui.use(['table','jquery','layer','form','tree'], function(){
        var table = layui.table;
        var $  = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var tree = layui.tree;

        //角色名表单验证
        $("#rolename").blur(function () {
            var rolename = $("#rolename").val();
            $.ajax({
                url:'${pageContext.request.contextPath}/role/getOneRole',
                type:"POST",
                data:{"rolename":rolename},
                dataType:"json",
                success:function (result) {
                    if (result.code==1){//名字不重复
                        $("#btnSub").attr("disabled",false);
                    }else{//名字重复
                        $("#btnSub").attr("disabled",true);
                        layer.msg(result.msg);
                    }
                }
            })
        })

        /*角色校验*/
        form.verify({
            requiredname: function(value, item){ //value：表单的值、item：表单的DOM对象
                var rolename = $("#rolename").val()
                var message = '';
                var reg = /[a-zA-Z0-9_\u4e00-\u9fa5]+/;
                if (!reg.test(value)) {
                    return '格式有误！';
                }
                $.ajax({
                    url:'${pageContext.request.contextPath}/role/getOneRole',
                    type:"POST",
                    data:{"rolename":rolename},
                    dataType:"json",
                    success:function (result) {
                        if (result.code==1){//名字不重复
                        }else{//名字重复
                            message ="角色名已存在，请重新输入！"
                        }
                    }
                })
                if (message != '') {
                    return message;
                }
            }
        });

        //展示角色信息的方法
        /*function showtable(){*/
        table.render({
            id:'tb'
            ,elem: '#test'
            ,url:'${pageContext.request.contextPath}/role/findAll'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,title: '用户数据表'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'roleid', title:'ID', fixed: 'left', unresize: true, sort: true}
                ,{field:'rolename', title:'角色名'}
                ,{field:'remark', title:'角色描述'}
                ,{field:'status', title:'状态',  sort: true,templet: function(d){
                        if (d.status==0){
                            return '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger">禁用</button>';
                        }else{
                            return '<button type="button" class="layui-btn layui-btn-xs">启用</button>';
                        }
                    }}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo'}
            ]]
            , page: true
            , limit: 10 //默认每页显示5条
            , limits:[2,5,10,15]
        });
        /*}*/



        //新增和修改角色的表单提交事件
        form.on('submit(editRole)', function (data){
            var roleData = form.val("editForm");
            $.ajax({
                type: "post",
                url: "${pageContext.request.contextPath}/role/addOrUpdate",
                dataType: 'json',
                async:false,
                data:roleData,
                success: function (result) {
                    //alert(result!=null);
                    layer.closeAll();//关闭弹框
                    if (result.code == 200 ){
                        layer.msg(result.msg);
                    }else{
                        layer.msg(result.msg);
                    }
                    table.reload('tb');
                }
            });
        });



        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'addRole':
                    //打开弹出框时先清空
                    $("#editForm")[0].reset();
                    layer.open({
                        type: 1,
                        anim: 3,
                        title: ['添加角色', 'font-size:20px'],
                        content: $("#editForm"),
                        offset: '50px',
                        area: '400px'
                    })
                    break;
                case 'refresh':
                    table.reload('tb');//刷新表格
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听行工具事件
        var rowData;
        table.on('tool(test)', function(obj){
            var data = obj.data;
            rowData = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除吗', function(index){
                    if (data.status == 0) {
                        $.ajax({
                            type:'post',
                            url:'${pageContext.request.contextPath}/role/delById',
                            data:{'roleid':data.roleid},
                            dataType: 'json',
                            success:function (result){
                                layer.closeAll();
                                if (result.code == 1) {
                                    layer.msg(result.msg)
                                }else {
                                    layer.msg(result.msg)
                                }
                                table.reload('tb');
                            }
                        })
                    }else {
                        layer.msg("启用状态，无法删除！")
                    }
                    layer.close(index);
                });
            } else if(obj.event === 'edit') {
                //打开弹出框时先清空
                $("#editForm")[0].reset();
                layer.open({
                    type: 1,
                    anim: 3,
                    title: ['修改角色', 'font-size:20px'],
                    content: $("#editForm"),
                    offset: '50px',
                    area: '400px',
                    success:function (){
                        form.val("editForm",data);//点击编辑时，填充数据
                    }
                })
            }else if (obj.event==='editPermission'){//修改权限的弹出框
                layer.open({
                    type: 1,
                    anim: 3,
                    offset: '50px',
                    title: ['修改权限', 'font-size:20px'],
                    content: $("#treeDemo")
                })
                //打开弹出框之后，查询所有权限信息，用来填充权限树
                $.ajax({
                    type:'get',
                    url:'${pageContext.request.contextPath}/menu/treeMenu',
                    success:function (treeData) {
                        //权限查询成功后，填充权限树
                        tree.render({
                            elem: '#test1'
                            ,data: treeData.data
                            ,showCheckbox: true
                            ,id:'demoId'
                            ,isJump: true //是否允许点击节点时弹出新窗口跳转
                        });

                        //当树形菜单填充完毕后，再将当前角色对应的所有权限的mid查询出来，用于勾选已知权限使用。
                        $.ajax({
                            type:'get',
                            url:'${pageContext.request.contextPath}/menu/findRoleMenuId',
                            data:{"roleid":rowData.roleid},
                            dataType:'json',
                            success:function (midArr) {
                                //执行勾选操作
                                tree.setChecked('demoId',midArr.data); //批量勾选
                            }
                        })
                    }
                })
            }

        });

        //点击提交修改权限按钮 做修改权限操作
        $("#subPer").click(function () {
            //取出勾选的节点的id数据，父子节点都要
            var checkData = tree.getChecked("demoId");
            var midArr = [];
            $.each(checkData,function (i,obj1) {
                //将勾选的父菜单的id放入数组中
                midArr.push(obj1.id);
                $.each(obj1.children,function (i,obj2) {
                    //将所有勾选的子菜单的id放入数组中
                    midArr.push(obj2.id);
                })
            })

            $.ajax({
                type:'post',
                url:"${pageContext.request.contextPath}/menu/updatePermission",
                data:{"roleid":rowData.roleid,"midArr":midArr+""},
                dataType:'json',
                success:function (result) {
                    layer.closeAll();
                    if(result.code==1){
                        layer.msg(result.msg,{icon:1});
                    }else{
                        layer.msg(result.msg,{icon:5});
                    }
                }
            })
        })
    });
</script>
</body>
</html>
